﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Reflection;
using System.IO;
using System.Drawing.Imaging;

namespace GWHandCalendarManilaSettingTool
{
    class ExtractIcon
    {
        public static Bitmap GetBitmapFromExeIcon(string path)
        {
            return GetBitmap(GetIconFromExe(path));
        }

        public static Icon GetIconFromExe(string path)
        {
            return GetIconFromExe(path, true);
        }

        //http://www.pinvoke.net/default.aspx/shell32/ExtractIconEx.html
        public static Icon GetIconFromExe(string path, bool large)
        {
            IntPtr hLargeIcon = IntPtr.Zero;
            IntPtr hSmallIcon = IntPtr.Zero;
            ExtractIconEx(path, 0, ref hLargeIcon, ref hSmallIcon, 1);
            if (large)
            {
                return (Icon)Icon.FromHandle(hLargeIcon).Clone();
            }
            else
            {
                return (Icon)Icon.FromHandle(hSmallIcon).Clone();
            }
        }

        //http://social.msdn.microsoft.com/Forums/en-US/netfxcompact/thread/e765775c-a5b5-493f-baeb-3eaee1d41cef
        public static Bitmap GetBitmap(Icon icon)
        {
            Bitmap bmp = new Bitmap(icon.Width, icon.Height);

            //Create temporary graphics
            Graphics gxMem = Graphics.FromImage(bmp);

            //Draw the icon
            gxMem.DrawIcon(icon, 0, 0);

            //Clean up
            gxMem.Dispose();

            return bmp;
        }

        //http://msdn.microsoft.com/en-us/library/aa922154.aspx
        [DllImport("coredll.dll", SetLastError = true)]
        private static extern IntPtr ExtractIconEx(string fileName, int index, ref IntPtr hIconLarge, ref IntPtr hIconSmall, uint nIcons);

        /// <summary>
        /// Draws the image with transparency
        /// </summary>
        /// <param name="gx">Destination graphics</param>
        /// <param name="image">The image to draw</param>
        /// <param name="destRect">Desctination rectangle</param>
        //public static void DrawImageTransparentF(this Graphics gx, Image image, Rectangle destRect)
        public static void DrawImageTransparent(Graphics gx, Image image, Rectangle destRect)
        {
            ImageAttributes imageAttr = new ImageAttributes();
            Color transpColor = GetTransparentColor(image);
            imageAttr.SetColorKey(transpColor, transpColor);
            gx.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttr);
            //imageAttr.Dispose();//.net cf2 不可用
            imageAttr = null;
        }
        private static Color GetTransparentColor(Image image)
        {
            return ((Bitmap)image).GetPixel(image.Width - 1, image.Height - 1);
        }
    }
}
